#include <iostream>
#include <unordered_set>
#include <string>
#include <queue>
using namespace std;
class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> wordSet(wordList.begin(), wordList.end());
        if (!wordSet.count(endWord)) return 0;
        queue<string> q;
        q.push(beginWord);
        int steps = 1;
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                string curr = q.front();
                q.pop();
                if (curr == endWord) return steps;
                for (int j = 0; j < curr.size(); j++) {
                    char original = curr[j];
                    for (char ch = 'a'; ch <= 'z'; ch++) {
                        if (ch == original) continue;

                        curr[j] = ch;
                        if (wordSet.count(curr)) {
                            wordSet.erase(curr);
                            q.push(curr);
                        }
                    }
                    curr[j] = original; 
                }
            }
            steps++;
        }

        return 0;
    }
};